#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/4/10 14:17
# @Author  : harry
import requests
from rest_framework import serializers

from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet
from dvadmin_wechat.models import OfficialAccountManagement


class OfficialAccountManagementCreateSerializer(CustomModelSerializer):
    class Meta:
        model = OfficialAccountManagement
        fields = "__all__"
        read_only_fields = ["id"]

    def validate(self, attrs):
        request = self.context.get("request")
        appid = request.data.get("appid")
        app_secret = request.data.get("app_secret")
        # print(request.data)
        res = requests.get(
            url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}'.format(
                appid, app_secret))
        o_a_m = OfficialAccountManagement.objects.filter(appid=appid).first()
        if self.instance and self.instance.id:
            if o_a_m:
                if o_a_m.id != self.instance.id:
                    raise serializers.ValidationError("已有相同appid存在")
        else:
            if OfficialAccountManagement.objects.filter(appid=appid).first():
                raise serializers.ValidationError("已有相同appid存在")
        # print(res.text)
        if "access_token" in res.text:
            attrs['appid'] = appid
            attrs['app_secret'] = app_secret
        else:
            raise serializers.ValidationError(res.json().get("errmsg"))

        return attrs

class OfficialAccountManagementViewSet(CustomModelViewSet):
    """
    公众号管理
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = OfficialAccountManagement.objects.all()
    serializer_class = OfficialAccountManagementCreateSerializer
    create_serializer_class = OfficialAccountManagementCreateSerializer
    update_serializer_class = OfficialAccountManagementCreateSerializer
    search_fields = ['name', 'status', 'appid']
    filter_fields = ['name', 'status', 'appid']


